﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using DevExpress.XtraEditors;
using eFatura.Utility;
using Extensions;

namespace eFatura
{
    public partial class EDefter : XForm
    {
        public EDefter()
        {
            InitializeComponent();
        }
 

        string[] months = new string[12] {"Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"};

        private void EDefter_Load(object sender, EventArgs e)
        {
            for (int i = DateTime.Now.Year - 1; i <= DateTime.Now.Year + 1; i++)
                this.cb_Year.Properties.Items.Add(i);

            for (int i = 0; i < 12; i++)
                this.cb_Month.Properties.Items.Add(this.months[i]);

            this.cb_Year.SelectedText = DateTime.Now.Year.ToString();
            this.cb_Month.SelectedIndex = DateTime.Now.Month - 1;
            this.gc.Visible = false;
        }

        StringBuilder sb = new StringBuilder();

        public class Journal
        {
            public Header Header = new Header();
            public JournalItemList JournalItemList = new JournalItemList();


            public string Serialize()
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Journal));

                StringWriter textWriter = new Utf8StringWriter();
                
                xmlSerializer.Serialize(textWriter, this);
                string result = textWriter.ToString();

                result = result.Replace("\r\n    <EntryHeaders>", "");
                result = result.Replace("\r\n    </EntryHeaders>", "");

                result = result.Replace("\r\n        <EntryDetails>", "");
                result = result.Replace("\r\n        </EntryDetails>", "");
                 
                result =  result.Replace(@" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""","");
               // result = result.Replace("\r\n", "");

                return result;
            }

            public class Utf8StringWriter : StringWriter
            {
                public override Encoding Encoding
                {
                    get { return Encoding.UTF8; }
                }
            }
        }



        public class Header
        {
            public string PeriodStartDate = "";
            public string PeriodEndDate = "";
        }

        public class JournalItemList
        {
            public List<EntryHeader> EntryHeaders = new List<EntryHeader>();
            public EntryHeader AddEntryHeader()
            {
                EntryHeader eh = new EntryHeader();
                EntryHeaders.Add(eh);
                return eh;
            }
        }

        public class EntryHeader
        {
            public string EnteredBy= "";
            public string EnteredDate= "";
            public string EntryNumber= "";
            public string EntryComment= "";
            public string BatchID= "";
            public string BatchDescription= "";
            public string TotalDebit= "";
            public string TotalCredit= "";
            public string EntryNumberCounter= "";


            public List<EntryDetail> EntryDetails = new List<EntryDetail>();

            public EntryDetail AddEntryDetail()
            {
                EntryDetail ed = new EntryDetail();
                EntryDetails.Add(ed);
                return ed;
            }
        }

        public class EntryDetail
        {
            public string LineNumber= "";            
            public string LineNumberCounter= "";
            public string AccountMainID= "";
            public string AccountMainDescription= "";
            public string AccountSubID= "";
            public string AccountSubDescription= "";
            public string Amount= "";
            public string DebitCreditCode= "";
            public string PostingDate= "";
            public string DocumentType= "";
            public string DocumentTypeDescription= "";
            public string DocumentNumber= "";
            public string DocumentReference= "";
            public string DocumentDate= "";
            public string PaymentMethod= "";
            public string DetailComment= "";
        }


        private void btnReport_Click(object sender, EventArgs e)
        {            
            this.Cursor = Cursors.WaitCursor;

          
            //DataTable dt = AppSession.DataManager.ExecuteDataTable(Schema + "GetEDefter" , deBaslangic.DateTime,deBitis.DateTime);

            DateTime startDate = new DateTime(Convert.ToInt32(this.cb_Year.SelectedItem),
                                              this.cb_Month.SelectedIndex + 1,
                                              1);

            DateTime endDate = new DateTime(Convert.ToInt32(this.cb_Year.SelectedItem),
                                            this.cb_Month.SelectedIndex + 1,
                                            DateTime.DaysInMonth(Convert.ToInt32(this.cb_Year.SelectedItem), this.cb_Month.SelectedIndex + 1));


            DataTable dt = AppSession.DataManager.ExecuteDataTable(AppSession.Schema + "GetEDefter", startDate, endDate); 

            gv.Init(dt);

            Journal journal = new Journal();

            journal.Header.PeriodStartDate = startDate.ToString("yyyy-MM-dd");
            journal.Header.PeriodEndDate = endDate.ToString("yyyy-MM-dd");

            string yevmiyeNo = "";
            EntryHeader eh = null;

            int index = seIndex.EditValue.ToIntNN();
            foreach (DataRow dr in dt.Rows)
            {
                index++;

                if (dr["YevmiyeNo"].ToStringNN().Trim() == "0")
                {
                    XtraMessageBox.Show("Yevmiye numarası '0' olan kayıt bulunmaktadır. Bu alanı 1'den başlayıp birer aratacak şekilde sıralayınız.", "e-Defter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.Cursor = Cursors.Default;
                    return;
                }

                if (yevmiyeNo != dr["YevmiyeNo"].ToStringNN().Trim())
                {
                    yevmiyeNo = dr["YevmiyeNo"].ToStringNN().Trim();

                    eh = journal.JournalItemList.AddEntryHeader();
                    eh.EnteredBy = dr["KaydiAcan"].ToStringNN().Trim().Length < 2 ? "nu" : dr["KaydiAcan"].ToStringNN().Trim().Substring(0, 2);
                    eh.EnteredDate = ((DateTime)dr["FisTarihi"]).ToString("yyyy-MM-dd");
                    eh.TotalCredit = dt.Compute("sum(Alacak)", "YevmiyeNo = " + yevmiyeNo).ToStringNN().Trim().Replace(",", ".");
                    eh.TotalDebit = dt.Compute("sum(Borc)", "YevmiyeNo='" + yevmiyeNo + "'").ToStringNN().Trim().Replace(",", ".");
                    eh.EntryComment = dr["FisAciklama"].ToStringNN();
                    eh.EntryNumber = dr["FisNo"].ToStringNN();
                    eh.EntryNumberCounter = yevmiyeNo;
                }

                EntryDetail ed = eh.AddEntryDetail();
                ed.LineNumber = index.ToString();
                ed.LineNumberCounter = yevmiyeNo;

                ed.AccountMainID = dr["AnaHesapKodu"].ToStringNN().Trim();
                ed.AccountMainDescription = dr["AnaHesapKoduAciklama"].ToStringNN().Trim();

                ed.AccountSubID = dr["HesapKodu"].ToStringNN().Trim();
                ed.AccountSubDescription = dr["HesapAciklama"].ToString().Trim();

                ed.DebitCreditCode = dr["BorcAlacak"].ToStringNN().Trim();
                ed.PostingDate = ((DateTime)dr["FisTarihi"]).ToString("yyyy-MM-dd").Trim();

                ed.Amount = ed.DebitCreditCode == "D" ? dr["Borc"].ToStringNN().Trim().Replace(",", ".") : dr["Alacak"].ToString().Trim().Replace(",", ".");

                ed.DetailComment = dr["FisAciklama"].ToStringNN();
                ed.DocumentReference = dr["FisNo"].ToStringNN(); 
            }
               
            SaveFileDialog saver = new SaveFileDialog();
            saver.FileName = "e-defter_" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".xml";
            saver.Filter = "e-defter XML|*.xml";
            if (saver.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                File.WriteAllText(saver.FileName, journal.Serialize());
                XtraMessageBox.Show("Dosya başarıyla kaydedildi. Portalde kullanabilirsiniz.", "e-Defter", MessageBoxButtons.OK,MessageBoxIcon.Information);
                if (AppSession.UserInfo.UserId == 1)
                    System.Diagnostics.Process.Start(saver.FileName);                    
            }

            this.Cursor = Cursors.Default;
        }
    }
}
